use anyhow::Result;
use git2::{DiffOptions, Repository};
use smart_git_commit_ai::generate_commit_message_by_git_diff;
use std::env;
use std::path::{Path, PathBuf};

fn get_git_diff_content(repo_path: Option<&Path>) -> Result<String> {
    // 如果没有提供路径，使用当前目录
    let path = repo_path
        .map(PathBuf::from)
        .unwrap_or_else(|| env::current_dir().expect("Failed to get current directory"));

    // 打开仓库
    let repo = Repository::open(&path)?;

    // 获取当前的索引
    let mut index = repo.index()?;

    // 创建一个空的树对象，代表当前的索引状态
    let tree_id = index.write_tree()?;
    let tree = repo.find_tree(tree_id)?;

    // 设置 diff 选项
    let mut diff_opts = DiffOptions::new();
    diff_opts
        .include_untracked(true)
        .recurse_untracked_dirs(true);

    // 获取工作目录和索引之间的差异
    let diff = repo.diff_tree_to_workdir_with_index(Some(&tree), Some(&mut diff_opts))?;

    // 将 diff 转换为字符串
    let mut diff_content = String::new();
    diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
        use std::str;
        if let Ok(content) = str::from_utf8(line.content()) {
            diff_content.push_str(content);
        }
        true
    })?;

    Ok(diff_content)
}

fn main() -> Result<()> {
    let _diff_content = get_git_diff_content(None).unwrap();
    let _commit_message = generate_commit_message_by_git_diff(&_diff_content)?;
    println!("Hello, Smart Git Commit");
    println!("diff_content: {}", _diff_content);
    println!("----------------------");
    println!("commit_message: {}", _commit_message);

    Ok(())
}
